var defaultParams; //默认选中行
var menuId; //菜单栏父元素ID
var tableData; //定义列表名称
var sumFile = 0;
// 详情
function detail() {
    if (defaultParams) {

        $("#completeSubmit").attr("disabled", false)
        $("#submitDepartChoose").attr("disabled", false)
        $("#buttonDetail").hide()
        $("#buttonGet").hide()
        $("#buttonBack").show()
        $(".buttonSearchBox").hide()
        $(".bootstrap-table").eq(0).hide()
        $(".bootstrap-table").eq(1).show()
        $(".contentInput").eq(0).show()
        $(".Isdisabled input").attr("disabled", true)
        $(".Isdisabled select").attr("disabled", true)
        $(".Isdisabled textarea").attr("disabled", true)
        $("#submitButton").hide()
        $("#saveButton").hide()
        $("#submitMan").attr("disabled", true)
        $("#submitMan").val(localStorage.getItem("userName"))

        modifyVsdetailData()

    } else {
        layer.msg('请选择一项查看');
    }
}

//返回
function back() {
    $("#buttonDetail").show()
    $("#buttonAdd").show()
    $("#buttonModify").show()
    $("#buttonDelete").show()
    $("#buttonBack").hide()
    $("#buttonGet").show()
    $(".buttonSearchBox").show()
    $(".bootstrap-table").eq(0).show()
    $(".bootstrap-table").eq(1).hide()
    $(".contentInput").hide()
    defaultParams = "" //每次返回 清空上次选择
    $("#table").bootstrapTable('refresh');

}

// 修改和详情数据
function modifyVsdetailData() {
    $.ajax({
        type: "get",
        url: "/operation/event/pending/info",
        dataType: "json",
        data: { "eventId": defaultParams.eventId },
        cache: false,
        success: function(msg) {
            $("#eventCode").val(msg.data.eventId)
            $("#subbmitMan").val(msg.data.insertUserName)
            $("#phone").val(msg.data.tel)
            $("#organiza").val(msg.data.orgName)
            $("#eventTitle").val(msg.data.eventTheme)
            $("#eventDesc").val(msg.data.eventDetail)
        },
        error: function(e) {
            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    })

    // 
    $.ajax({
            type: "get",
            url: "/operation/event/flow/file/submitProcess",
            dataType: "json",
            data: { "eventId": defaultParams.eventId },
            cache: false,
            success: function(data) {
                var str = ""
                for (var i = 0; i < data.data.length; i++) {
                    var dealFileName = data.data[i].fileName
                    str += '  <a   fileId="' + data.data[i].eventFlowFileId + '"  data-toggle="tooltip" data-placement="top" title="' + dealFileName + '" class="ieDeal attachFile col-md-3 col-sm-3 col-xs-3  btn btn-success" href="/operation/event/flow/file/download?fileId=' + data.data[i].eventFlowFileId + '">' + dealFileName + '</a>'
                }
                $(".attachFileBoxShow").html(str)
                $("[data-toggle='tooltip']").tooltip()
            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        // 系统通道和问题类别
    $.ajax({
        type: "get",
        url: "/operation/channel/getChannelByMenu",
        dataType: "json",
        contentType: 'application/json',
        data: { "menuId": menuId },
        cache: false,
        success: function(msg) {
            systermRouteData("#systermRoute", msg.data)
                // 问题类别数据
            $.ajax({
                type: "get",
                url: "/operation/question/getQuestionByMenuAndChannel",
                dataType: "json",
                contentType: 'application/json',
                cache: false,
                data: { "menuId": menuId, "channelId": $("#systermRoute option:selected").attr("channelId") },
                success: function(msg) {
                    problemTypeData("#problemType", msg.data)
                },
                error: function(e) {
                    if (e.status == 500) {
                        layer.msg("系统错误");
                        return
                    } else if (e.responseText) {
                        var errorMessage = JSON.parse(e.responseText).errors[0].message;
                        layer.msg(errorMessage);
                    }
                }
            });
        },
        error: function(e) {
            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    });

    // 第二表单信息
    $.ajax({
            type: "get",
            url: "/operation/event/pending/transformInfo",
            dataType: "json",
            data: { "eventId": defaultParams.eventId },
            cache: false,
            success: function(msg) {
                if (msg.data.showTransform) {
                    $(".chooseFileButton").show()
                    $("#file").show()
                    $(".upload").show()
                    $("#problemDeleve").parent().show()
                    $("#completeSubmit").show()
                    $("#returnBack").show()
                    $("#dealSuggest").attr("disabled", false)
                    $(".attachFileBoxShow2").hide()


                } else {
                    $("#file").hide()
                    $(".chooseFileButton").hide()
                    $(".upload").hide()
                    $("#problemDeleve").parent().hide()
                    $("#completeSubmit").hide()
                    $("#returnBack").hide()
                    $("#dealSuggest").attr("disabled", true)
                    $("#dealSuggest").val(msg.data.processAdvice)
                    $(".attachFileBoxShow2").show()
                }
                if (msg.data.isSupportTransform == "0") { //不可分发
                    $("#problemDeleve").parent().hide()
                } else {
                    if (!msg.data.showTransform) {
                        $("#problemDeleve").parent().hide()
                    } else {
                        $("#problemDeleve").parent().show()
                    }

                }

            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        // 第2表单附件
    $.ajax({
            type: "get",
            url: "/operation/event/flow/file/curentProcess",
            dataType: "json",
            data: { "eventId": defaultParams.eventId },
            cache: false,
            success: function(data) {
                var str = ""
                for (var i = 0; i < data.data.length; i++) {
                    var dealFileName = data.data[i].fileName
                    str += ' <a fileId="' + data.data[i].eventFlowFileId + '"  data-toggle="tooltip" data-placement="top" title="' + dealFileName + '" class="attachFile col-md-3 col-sm-3 col-xs-3  btn btn-success"  href="/operation/event/flow/file/download?fileId=' + data.data[i].eventFlowFileId + '">' + dealFileName + '</a>'

                }

                $(".attachFileBox").html(str)
                $("[data-toggle='tooltip']").tooltip()
            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        // 第三部分表单数据
    $.ajax({
            type: "get",
            url: "/operation/event/processed/solveInfo",
            dataType: "json",
            data: { "eventId": defaultParams.eventId },
            cache: false,
            success: function(msg) {
                if (msg.data.showEnded) {
                    $("#form3").show()
                    $(".lineThrough").show()
                } else {
                    $("#form3").hide()
                    $(".lineThrough").hide()
                }
            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        //获取组织机构信息
    $.ajax({
            type: "get",
            url: "/operation/event/pending/getOrgs",
            dataType: "json",
            data: { "eventId": defaultParams.eventId },
            cache: false,
            success: function(msg) {
                var orgStr = ""
                for (var i = 0; i < msg.data.length; i++) {
                    orgStr += " <option value='" + msg.data[i].orgId + "''>" + msg.data[i].orgName + "</option>"
                }
                $("#departChooseVal").html(orgStr)

                $('#departChooseVal').searchableSelect();
                $(".searchable-select").eq(0).siblings('.searchable-select').remove()

            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        //清空处理意见数据
        $("#table2").bootstrapTable('destroy');
    tableData2.initData()

    //
}

// 操作记录

var tableData2 = {
    initData: function() {
        // 
        $('#table2').bootstrapTable({
            striped: true, //隔行变色
            showHeader: true,
            cache: false,
            escape: true,
            ajax: function(request) {
                $.ajax({
                    type: "get",
                    url: "/operation/event/flow/",
                    dataType: "json",
                    data: { "eventId": defaultParams.eventId },
                    cache: false,
                    success: function(msg) {
                        for (var i = 0; i < msg.data.length; i++) {
                            msg.data[i]["updateTime"] = moment(msg.data[i]["updateTime"]).format('YYYY-MM-DD HH:mm:ss')

                            if (msg.data[i]["status"] == "11") {
                                msg.data[i]["status"] = "已保存"
                            } else if (msg.data[i]["status"] == "12") {
                                msg.data[i]["status"] = "已提交"
                            } else if (msg.data[i]["status"] == "13") {
                                msg.data[i]["status"] = "已回退"
                            } else if (msg.data[i]["status"] == "21") {
                                msg.data[i]["status"] = "待处理"
                            } else if (msg.data[i]["status"] == "22") {
                                msg.data[i]["status"] = "已分发"
                            } else if (msg.data[i]["status"] == "23") {
                                msg.data[i]["status"] = "待确认"
                            } else if (msg.data[i]["status"] == "30") {
                                msg.data[i]["status"] = "已处理"
                            } else if (msg.data[i]["status"] == "90") {
                                msg.data[i]["status"] = "已解决"
                            } else if (msg.data[i]["status"] == "91") {
                                msg.data[i]["status"] = "未解决"
                            }
                        }
                        request.success({
                            row: msg.data
                        });
                        $('#table2').bootstrapTable('load', msg.data);
                    },
                    error: function(e) {
                        if (e.status == 500) {
                            layer.msg("系统错误");
                            return
                        } else if (e.responseText) {
                            var errorMessage = JSON.parse(e.responseText).errors[0].message;
                            layer.msg(errorMessage);
                        }
                    }
                });
            },
            columns: columns = [
                { field: 'eventFlowId', title: 'id', align: "center", width: "20%" },
                { field: 'updateTime', title: '提交时间', align: "center" },
                { field: 'updateUserName', title: '提交人', align: "center" },
                { field: 'status', title: '当前状态', align: "center" },
                { field: 'processAdvice', title: '处理意见', align: "center" }
            ]

        });
        // 
    }
}

//删除搜索关键字
function removeSearchVal() {
    $("#searchVal").val("")
    $("#searchVal").focus()
}
//enter搜索
function noNumbers(e) {
    var keynum;
    var keychar;

    keynum = window.event ? e.keyCode : e.which;
    if (keynum == "13") {
        search()
    }
}
//清空默认 
function delDefault(e) {
    if (e.value == "可支持事件编号、事件主题、提交时间、处理人、状态搜索") {
        e.value = ""
    }
}
//移除焦点默认添加
function showTips(e) {
    if (e.value.replace(/^\s*|\s*$/g, "")) {} else {
        e.value = "可支持事件编号、事件主题、提交时间、处理人、状态搜索"
    }
}

function search() {
    var searchval = $("#searchVal").val().indexOf("可支持事件编号、事件主题、提交时间、处理人、状态搜索") > -1 ? "" : $("#searchVal").val();
    $("#exportList").attr("href", encodeURI("/operation/event/pending/export?menuId=" + menuId + "&" + "search=" + searchval))
    defaultParams = ""
    $("#table").bootstrapTable('destroy');
    tableData.initData()
}
//领取
function buttonGet() {
    if (defaultParams) {
        // 
        if (defaultParams.status === "处理中") {
            layer.msg('已领取');

        } else if (defaultParams.insertUserId == localStorage.getItem("userId")) {
            layer.msg('不能领取自己的申请');
        } else {
            var params = { "eventId": defaultParams.eventId }
            $.ajax({
                type: "post",
                url: "/operation/event/pending/receive",
                contentType: 'application/json',
                data: JSON.stringify(params),
                dataType: "json",
                cache: false,
                success: function(data) {
                    layer.msg('已领取', { time: 1000, icon: 1 });
                    $("#buttonDetail").click()
                    $("#table").bootstrapTable('refresh');
                },
                error: function(e) {
                    if (e.status == 500) {
                        layer.msg("系统错误");
                        return
                    } else if (e.responseText) {
                        var errorMessage = JSON.parse(e.responseText).errors[0].message;
                        layer.msg(errorMessage);
                    }
                }
            })
        }

    } else {
        layer.msg('请选择领取对象');
    }
}


//问题类别数据渲染
function problemTypeData(id, arr) {
    // 根据系统通道约束
    var str = ""
    for (var i = 0; i < arr.length; i++) {
        if (arr[i]["questionName"] == defaultParams.questionName) {
            str += '  <option channelid="' + arr[i]["channelId"] + '" menuid="' + arr[i]["menuId"] + '" questionid="' + arr[i]["questionId"] + '"  selected value="' + arr[i]["questionName"] + '">' + arr[i]["questionName"] + '</option>'
        } else {
            str += '  <option channelid="' + arr[i]["channelId"] + '" menuid="' + arr[i]["menuId"] + '" questionid="' + arr[i]["questionId"] + '"  value="' + arr[i]["questionName"] + '">' + arr[i]["questionName"] + '</option>'
        }
    }
    $(id).html(str)
}

// 系统通道数据
function systermRouteData(id, arr) {
    var str = ''
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].channelName === defaultParams.channelName) {
            str += '  <option selected channelId="' + arr[i]['channelId'] + '">' + arr[i]['channelName'] + '</option>'
        } else {
            str += '  <option channelId="' + arr[i]['channelId'] + '">' + arr[i]['channelName'] + '</option>'
        }
    }

    $(id).html(str)
}

//删除或下载附件 
$(".attachFileBox").on("click", $(".glyphicon-remove"), function(e) {
    var eve = e || window.event;
    var objEle = eve.target || eve.srcElement;
    if (objEle.className == "deleteAttach glyphicon glyphicon-remove") {
        sumFile--;
        $(objEle).parent().next().remove()
        $(objEle).parent().remove()
        return false
    }
})

//change附件
function changeRes(target) {
    var buttonName = target.value.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi, "$1") + '.' + target.value.replace(/.+\./, "")
    $(".chooseFileButton").text(buttonName)
}
//上传
function upload() {
    if ($("#file").val()) {
        var target = document.getElementById("file")
        $("#formId").submit();
    } else {
        layer.msg('请选择上传文件');
    }

}
// 上传之后返回结果
$("#target").load(function() {
    var data = JSON.parse($($(this)[0].contentDocument.body).text())
    if (data.message == "文件不得大于5M") {
        layer.msg(data.message);
    } else {
        sumFile++
        if (sumFile > 10) {
            sumFile = 10
            layer.msg('最多可上传10个文件,请重新选择');

        } else { //可以上传
            var str = ""
            var dealFileName = data.data.fileName;
            str += ' <a fileId="' + data.data.fileId + '"  data-toggle="tooltip" data-placement="top" title="' + dealFileName + '" class="attachFile ieDeal col-md-3 col-sm-3 col-xs-3  btn btn-success"  href="/operation/event/flow/file/download?fileId=' + data.data.fileId + '">' + dealFileName + '<span class="deleteAttach glyphicon glyphicon-remove"></span></a>'
            $(".attachFileBox").append(str)
            layer.msg('上传成功', { time: 1000, icon: 1 });
            $("[data-toggle='tooltip']").tooltip()
        }

    }
    $(".chooseFileButton").text("选择附件")
    clearInput()
})


// 问题分发-机构选择提交
function submitDepartChooseEvent() {
    // $("#returnBack").attr("disabled", true)
    var filesId = []
    if ($(".attachFileBox .attachFile")) {
        for (var i = 0; i < $(".attachFileBox .attachFile").length; i++) {
            filesId.push($(".attachFileBox .attachFile").eq(i).attr("fileid"))
        }
    }
    var params = { "fileIds": filesId, "eventId": defaultParams.eventId, "processAdvice": $("#dealSuggest").val(), "orgId": $(".searchable-select-item.selected").attr("data-value") }

    $.ajax({
            type: "post",
            url: "/operation/event/pending/transform",
            contentType: 'application/json',
            data: JSON.stringify(params),
            dataType: "json",
            cache: false,
            success: function(data) {
                $("#submitDepartChoose").attr("disabled", true)
                layer.msg('成功', { time: 1000, icon: 1 });
                $("#table2").bootstrapTable('destroy');
                //隐藏机构与提交分发按钮
                $(".chooseOrg").hide()
                    // 显示提交分发按钮
                $("#problemDeleve").parent().show()
                $("#table2").bootstrapTable('destroy');
                tableData2.initData()
                back()
            },
            error: function(e) {
                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        // 

    $(".modal-footer button").eq(0).click()
}
// 详情页操作-完成提交
function completeSubmitEvent() {
    $("#completeSubmit").attr("disabled", true)
    var filesId = []
    if ($(".attachFileBox .attachFile")) {
        for (var i = 0; i < $(".attachFileBox .attachFile").length; i++) {
            filesId.push($(".attachFileBox .attachFile").eq(i).attr("fileid"))
        }
    }
    var params = { "fileIds": filesId, "eventId": defaultParams.eventId, "processAdvice": $("#dealSuggest").val() }
    $.ajax({
        type: "post",
        url: "/operation/event/pending/processedSubmit",
        contentType: 'application/json',
        data: JSON.stringify(params),
        dataType: "json",
        cache: false,
        success: function(data) {
            $(".chooseFileButton").text("选择附件")

            layer.msg('成功', { time: 1000, icon: 1 });
            $("#dealSuggest").val("")
            $("#table2").bootstrapTable('destroy');
            tableData2.initData()

            back()

        },
        error: function(e) {
            $("#completeSubmit").attr("disabled", false)
            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    })
}

//清除模态框数据
$('#myModalReturnBack').on('show.bs.modal', function(e) {
        $("#returnBackReason").val("")
    })
    // 回退提交  
function returnBackSubmit() {
    $("#returnBack").attr("disabled", true)
    var filesId = []
    if ($(".attachFileBox .attachFile")) {
        for (var i = 0; i < $(".attachFileBox .attachFile").length; i++) {
            filesId.push($(".attachFileBox .attachFile").eq(i).attr("fileid"))
        }
    }
    var params = { "fileIds": filesId, "eventId": defaultParams.eventId, "processAdvice": $("#dealSuggest").val() }

    $.ajax({
        type: "post",
        url: "/operation/event/pending/back",
        contentType: 'application/json',
        data: JSON.stringify(params),
        dataType: "json",
        cache: false,
        success: function(data) {
            layer.msg('回退成功', { time: 1000, icon: 1 });
            back()
        },
        error: function(e) {
            $("#returnBack").attr("disabled", false)
            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    })

}
// 点击问题分发，显示机构选择列表 自己隐藏
function chooseOrgShow() {
    $(".chooseOrg").show()
    $("#problemDeleve").parent().hide()
}
// 点击关闭，隐藏机构选择列表
function chooseOrgHide() {
    $(".chooseOrg").hide()
}
// 详情页操作-上报是否解决   
function submitLittleEvent() {

    var checkedVal = $('input:radio[name="inlineRadioOptions"]:checked').val()

    if (checkedVal) {
        var params = {
            "eventId": defaultParams.eventId,
            "solved": checkedVal == "true" ? true : false,
            "remark": $("#moreDeac").val()
        }

        $.ajax({
                type: "post",
                url: "/operation/event/pending/endSubmit",
                contentType: 'application/json',
                data: JSON.stringify(params),
                dataType: "json",
                cache: false,
                success: function(data) {
                    $("#submitLittleEvent").attr("disabled", true)
                    layer.msg('成功', { time: 1000, icon: 1 });
                    $("#moreDeac").val("")
                    back()
                },
                error: function(e) {
                    if (e.status == 500) {
                        layer.msg("系统错误");
                        return
                    } else if (e.responseText) {
                        var errorMessage = JSON.parse(e.responseText).errors[0].message;
                        layer.msg(errorMessage);
                    }
                }
            })
            // 
    } else {
        layer.msg('请选择是否解决');
    }
}


//清空input[type=file]
function clearInput() {
    var obj = document.getElementById("file");
    obj.outerHTML = obj.outerHTML;
}
